package com.tdkj.service.shop.impl;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanShelfCustomBuyDao;
import com.tdkj.model.financial.BeanConsumeRecord;
import com.tdkj.model.shop.BeanShelf;
import com.tdkj.model.shop.BeanShelfCustom;
import com.tdkj.model.shop.BeanShelfCustomBuy;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.ServiceException;
import com.tdkj.service.financial.IBeanConsumeRecordService;
import com.tdkj.service.shop.IBeanShelfCustomBuyService;

@Component
public class BeanShelfCustomBuyServiceImpl extends BaseService implements
		IBeanShelfCustomBuyService {
	
	IBeanShelfCustomBuyDao shelfCustomBuyDao;
	
	@Resource
	public void setShelfCustomBuyDao(IBeanShelfCustomBuyDao shelfCustomBuyDao) {
		this.shelfCustomBuyDao = shelfCustomBuyDao;
	}
	
	private IBeanConsumeRecordService consumeRecordService;
	
	@Resource
	public void setConsumeRecordService(
			IBeanConsumeRecordService consumeRecordService) {
		this.consumeRecordService = consumeRecordService;
	}

	@Override
	public BeanShelfCustomBuy add(Long userId, Long customId) throws ServiceException {
		BeanUser user = shelfCustomBuyDao.findById(userId, BeanUser.class);
		BeanShelfCustom custom = shelfCustomBuyDao.findById(customId, BeanShelfCustom.class);
		
		
		BeanShelfCustomBuy bean = new BeanShelfCustomBuy();
		bean.setUser(user);
		bean.setCustom(custom);
		bean.setBuyTime(new Timestamp(System.currentTimeMillis()));
		shelfCustomBuyDao.save(bean);
		
		if(user.getShop().getShelfs() != null && user.getShop().getShelfs().size() == 1){
			BeanShelf shelf = user.getShop().getShelfs().get(0);
			if(shelf.getQuantity() == null){
				shelf.setQuantity(0);
			}
			shelf.setQuantity(shelf.getQuantity() + custom.getQuantity());
		}
			
		
		consumeRecordService.create(userId, custom.getPrice().intValue(), custom.getUnit(), bean.getId(), BeanShelfCustomBuy.class, "货架购买");
		return bean; 
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BeanShelfCustomBuy> getBuyLogs(Long userId) {
		BeanUser user = shelfCustomBuyDao.findById(userId, BeanUser.class);
		List<BeanShelfCustomBuy> logs = shelfCustomBuyDao.getSession().createCriteria(BeanShelfCustomBuy.class).add(Restrictions.eq("user", user)).addOrder(Order.desc("buyTime")).list();
		return logs;
	}

}
